<template>
  <div class="login-wrap">
    <div class="login">
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="login-form-register"
      >
        <!-- <h3 class="title">{{ title }}</h3> -->

        <h3 class="title">{{ $t("login.accountRegistr") }}</h3>
        <el-form-item prop="userEmail">
          <el-input
            v-model="registerForm.userEmail"
            type="text"
            size="default"
            auto-complete="off"
            ref="emailInputRef"
            :placeholder="$t('login.email')"
          >
            <template #prefix>
              <svg-icon name="email" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            v-model="registerForm.code"
            auto-complete="off"
            size="default"
            :placeholder="$t('login.captcha')"
            style="width: 63%"
            @keyup.enter="handleRegister"
          >
            <template #prefix>
              <svg-icon name="validCode" />
            </template>
          </el-input>
          <div class="register-code ml10">
            <!-- <img :src="codeUrl" @click="getCode" class="register-code-img" /> -->
            <el-button
              plain
              class="register-code-img"
              :disabled="isDisabled"
              @click="getCode"
              >{{ getCodeText }}</el-button
            >
          </div>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            type="text"
            size="default"
            auto-complete="off"
            :placeholder="$t('login.account')"
          >
            <template #prefix>
              <svg-icon name="user" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            size="default"
            auto-complete="off"
            :placeholder="$t('login.password')"
            @keyup.enter="handleRegister"
          >
            <template #prefix>
              <svg-icon name="password" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            size="default"
            auto-complete="off"
            :placeholder="$t('user.confirmPwd')"
            @keyup.enter="handleRegister"
          >
            <template #prefix>
              <svg-icon name="password" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="agree">
          <el-checkbox
            v-model="registerForm.agree"
            style="width: 0px; font-size: 2px; margin-right: 24px"
          />
          <span style="font-size: 2px">我已阅读并同意</span>
          <el-link
            type="primary"
            @click="toAccountGreement"
            style="font-size: 2px"
            >《账号使用协议》</el-link
          >
          <el-link
            type="primary"
            @click="toPrivacyGreement"
            style="font-size: 2px"
            >《隐私政策》</el-link
          >
        </el-form-item>
        <el-form-item style="width: 100%">
          <el-button
            :loading="loading"
            type="primary"
            size="default"
            round
            style="width: 100%"
            @click.prevent="handleRegister"
          >
            <span v-if="!loading">{{ $t("login.register") }}</span>
            <span v-else>{{ $t("login.registering") }}...</span>
          </el-button>
        </el-form-item>
        <div style="text-align: center">
          <router-link class="link-type" :to="'/login'">{{
            $t("login.log_in_with_an_existing_account")
          }}</router-link>
        </div>
      </el-form>
    </div>

    <!--  底部  -->
    <div class="el-register-footer">
      <div v-html="copyRight"></div>
    </div>
  </div>
</template>

<script setup name="register">
import { getEmailCode, register } from "@/api/system/login";
import LangSelect from "@/components/LangSelect/index.vue";
import defaultSettings from "@/settings";
import { ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const codeUrl = ref("");
const registerForm = reactive({
  userEmail: "",
  username: "",
  password: "",
  confirmPassword: "",
  code: "",
  uuid: "",
  agree: false,
});

const getCodeText = ref("发送验证码");
const isDisabled = ref(false);
const countdown = ref(0);

const registerFormRef = ref(null);
const loading = ref(false);
const equalToPassword = (rule, value, callback) => {
  if (registerForm.password !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};
const registerRules = reactive({
  userEmail: [
    {
      required: true,
      type: "email",
      message: "请输入正确的邮箱地址",
      trigger: ["blur", "change"],
    },
  ],
  username: [
    { required: true, trigger: "blur", message: "请输入您的账号" },
    {
      validator: (rule, value, callback) => {
        const regex = /^[a-zA-Z0-9_.@]{6,32}$/;
        if (!regex.test(value)) {
          callback(new Error("账号由6-32位字母、数字或下划线或点或@组成"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  password: [
    { required: true, trigger: "blur", message: "请输入您的密码" },
    {
      validator: (rule, value, callback) => {
        const regex =
          /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>])[A-Za-z\d!@#$%^&*(),.?":{}|<>]{8,16}$/;
        if (!regex.test(value)) {
          callback(new Error("用户密码由8-16位大小写字母、数字、符号组合"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, trigger: "blur", message: "请再次输入您的密码" },
    { required: true, validator: equalToPassword, trigger: "blur" },
  ],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
  agree: [
    {
      trigger: "change",
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请接受服务条款"));
        } else {
          callback();
        }
      },
    },
  ],
});
const copyRight = computed(() => {
  return defaultSettings.copyright;
});
const title = computed(() => {
  return defaultSettings.title;
});
function toAccountGreement() {
  window.open("/agreement/account");
}
function toPrivacyGreement() {
  window.open("/agreement/privacy");
}
async function getCode() {
  if (isDisabled.value) return;
  isDisabled.value = true;
  const inputEmail = registerForm.userEmail;
  if (!validateEmail(inputEmail)) {
    proxy.$modal.msgError("请输入有效的邮箱地址");
    selectEmailInput();
    isDisabled.value = false;
    return;
  }
  const exists = await checkEmailExists(inputEmail);
  if (!exists) {
    proxy.$modal.msgError("该邮箱不存在");
    selectEmailInput();
    isDisabled.value = false;
    return;
  }
  countdown.value = 60;
  getCodeText.value = `${countdown.value} 秒后重试`;
  const timer = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--;
      getCodeText.value = `${countdown.value} 秒后重试`;
    } else {
      clearInterval(timer);
      isDisabled.value = false;
      getCodeText.value = "获取验证码";
    }
  }, 1000);
}
const emailInputRef = ref(null);
const selectEmailInput = () => {
  emailInputRef.value.select(); // 聚焦输入框
};
// 模拟判断邮箱是否存在的异步请求
const checkEmailExists = async (email) => {
  // 这里只是模拟，实际使用时应替换为真实的 API 请求
  return new Promise((resolve, reject) => {
    try {
      let dto = {
        email: email,
      };
      getEmailCode(dto)
        .then((res) => {
          console.log(res);
          if (res.code == 200) {
            resolve(true);
          } else {
            reject(false);
          }
        })
        .catch((err) => {
          ElMessageBox.confirm(
            "检测到您的邮箱已注册过商业化账号，是否使用改邮箱？",
            "系统提示",
            {
              confirmButtonText: "前往登录",
              cancelButtonText: "重新输入邮箱",
              type: "warning",
            }
          )
            .then(() => {
              isDisabled.value = false;
              router.push("/login");
            })
            .catch(() => {
              isDisabled.value = false;
              getCodeText.value = "获取验证码";
              countdown.value = 0;
              selectEmailInput();
            });
        });
    } catch {
      reject(false);
    }
  });
};

// 校验邮箱格式
const validateEmail = (email) => {
  const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return regex.test(email);
};
function handleRegister() {
  proxy.$refs["registerFormRef"].validate((valid) => {
    if (valid) {
      loading.value = true;
      register(registerForm)
        .then((res) => {
          if (res.code == 200) {
            const username = registerForm.username;
            ElMessageBox.alert(
              "<font color='red'>恭喜你，您的账号 " +
                username +
                " 注册成功！</font>",
              "系统提示",
              {
                dangerouslyUseHTMLString: true,
                type: "success",
              }
            )
              .then(() => {
                router.push("/login");
              })
              .catch(() => {});
          }
        })
        .catch(() => {
          loading.value = false;
        });
    }
  });
}
</script>

<style rel="stylesheet/scss" lang="scss">
@use "@/assets/styles/login.scss";
.register {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-size: cover;
  flex-direction: column;
  background: radial-gradient(
    220% 105% at top center,
    #1b2947 10%,
    #4b76a7 40%,
    #81acae 65%,
    #f7f7b6
  );
}
.login-form-register {
  padding: 15px 25px 15px 25px;
  height: 440px;
}
.title {
  margin: 0px auto 25px auto;
  text-align: center;
  // color: #fff;
}

.register-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.register-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-register-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #999999;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.register-code-img {
  height: 38px;
  width: 124px;
}
</style>
